package com.polaris.live.ui.login

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.view.KeyEvent
import android.view.View
import com.polaris.live.common.cacha.CacheUtil
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.constant.BizEventConst
import com.polaris.live.common.event.EventStringMessage
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ImmersionBarBuilder
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.TrackEventConst
import com.polaris.live.constant.TrackEventConst.EVENT_NEXT_UC
import com.polaris.live.databinding.ActivityLoginGmailBinding
import com.polaris.live.dialog.GlobalDialogManager
import com.polaris.live.interface_bag.TextWatcherAdapter
import com.polaris.live.ui.login.verify.InputPasswordActivity
import com.polaris.live.ui.login.verify.SetPasswordActivity
import com.polaris.live.ui.login.verify.VerifyActivity
import com.polaris.live.utils.TrackHelper
import com.polaris.live.viewmodel.login.PhoneNumberModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * gmail登录页
 *
 * @author Created by lucas on 2024/3/22 03:35
 * @since 1.2.0
 */
class GmailLoginActivity : BaseGoogleLoginActivity<PhoneNumberModel, ActivityLoginGmailBinding>() {

    override fun ImmersionBarBuilder.buildImmersionBar() {
        setTitleBar(mBinding.bvTitle)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        EventBus.getDefault().register(this)

        initListener()
        initObserve()

        val gmail = CacheUtil.getLastGmail()
        if (gmail != null) {
            mBinding.etGmail.setText(gmail)
            mBinding.gmailClear.visibility = View.VISIBLE
            mBinding.loginButton.alpha = 1f
        }
    }

    private fun initListener() {
        mBinding.etGmail.addTextChangedListener(object : TextWatcherAdapter() {
            override fun afterTextChanged(s: Editable?) {
                val toString = s?.toString() ?: return

                val trimmedStr = toString.replace("\\s+".toRegex(), "")  // 去掉所有空格

                if (trimmedStr.isEmpty()) {
                    mBinding.loginButton.alpha = AppConst.NOTCLICK
                } else {
                    mBinding.loginButton.alpha = 1.0f
                }
                if (toString.isEmpty()) {
                    mBinding.gmailClear.visibility = View.INVISIBLE
                } else {
                    mBinding.gmailClear.visibility = View.VISIBLE
                }
            }
        })

        mBinding.loginButton.setOnSingleClickListener {
            TrackHelper.trackActivity(this, EVENT_NEXT_UC)
            val text = mBinding.etGmail.text?.toString() ?: return@setOnSingleClickListener

            val gmail = text.replace("\\s+".toRegex(), "")  // 去掉所有空格
            if (gmail.isNotEmpty()) {
                mViewModel.isGmailRegistered(gmail)
            }
        }
        mBinding.selectGoogleLogin.setOnSingleClickListener {
            TrackHelper.trackActivity(this, TrackEventConst.EVENT_LOGIN_GOOGLE_UC)
            gotoGoogleLogin()
        }

        mBinding.gmailClear.setOnSingleClickListener {
            mBinding.etGmail.setText("")
        }

        mBinding.bvTitle.setOnLeftClientListener {
            TrackHelper.trackActivity(this, TrackEventConst.EVENT_RETURN_UC)
            finish()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        TrackHelper.trackActivity(this, TrackEventConst.EVENT_RETURN_UC)
        return super.onKeyDown(keyCode, event)
    }

    private fun initObserve() {
        mViewModel.isRegisteredLiveData.observe(this) { resultState ->
            parseState(resultState, { resp ->
                val intent = Intent()
                if (resp.registered == false) {
                    //转跳验证码
                    verifyGoogle {
                        intent.setClass(this, VerifyActivity::class.java)
                        if (it != null) {
                            intent.putExtra("googleValidate", it)
                        }
                        gotoLogin(intent)
                    }
                } else {
                    //转跳 设置密码 或者 输入密码
                    if (resp.hasPassword == false) {
                        verifyGoogle {
                            intent.setClass(this, SetPasswordActivity::class.java)
                            intent.putExtra("isLogin", true)
                            intent.putExtra("isFirstSet", true)
                            if (it != null) {
                                intent.putExtra("googleValidate", it)
                            }
                            gotoLogin(intent)
                        }
                    } else {
                        intent.setClass(this, InputPasswordActivity::class.java)
                        gotoLogin(intent)
                    }
                }
            }, {
                if (it.errCode == CommonConst.ErrorCode.SEAL_ACCOUNT || it.errCode == CommonConst.ErrorCode.SEAL_ACCOUNT_LOGIN || it.errCode == CommonConst.ErrorCode.SEAL_ACCOUNT_STOP) {
                    GlobalDialogManager.showSealAccountDialog(this, JsonUtils.toJson(it.ext))
                } else {
                    ToastGravity.showGravity(it.errorMsg)
                }
            })
        }
    }

    private fun gotoLogin(intent: Intent) {
        val toString = mBinding.etGmail.text?.toString() ?: return
        val gmail = toString.replace("\\s+".toRegex(), "")  // 去掉所有空格

        intent.putExtra("gmail", gmail)
        startActivity(intent)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEventBus(event: EventStringMessage) {
        when (event.from) {
            BizEventConst.LOGIN_FINISH -> {
                finish()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}